package org.csu.onlineedubackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.entity.Course;
import org.csu.onlineedubackend.entity.CourseBookmark;
import org.csu.onlineedubackend.mapper.CourseBookmarkMapper;
import org.csu.onlineedubackend.mapper.CourseMapper;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/courses")
@Slf4j
public class CourseBookmarkController {

    @Autowired
    private CourseBookmarkMapper courseBookmarkMapper;
    
    @Autowired
    private CourseMapper courseMapper;

    /**
     * 查询课程收藏状态
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @return 是否已收藏
     */
    @GetMapping("/{courseId}/bookmark")
    public CommonResponse<Boolean> isBookmarked(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId) {
        log.info("检查课程是否已收藏 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("检查课程收藏状态失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("检查课程收藏状态失败 - 课程不存在, 课程ID: {}", courseId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
            }
            
            QueryWrapper<CourseBookmark> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id", courseId).eq("student_id", studentId);
            Long count = courseBookmarkMapper.selectCount(wrapper);
            
            boolean isBookmarked = count != null && count > 0;
            log.info("课程收藏状态 - 课程ID: {}, 学生ID: {}, 是否已收藏: {}", courseId, studentId, isBookmarked);
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", isBookmarked);
        } catch (Exception e) {
            log.error("查询课程收藏状态异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
            System.out.println("查询课程收藏状态异常详细信息：");
            e.printStackTrace();
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加课程收藏
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @return 操作结果
     */
    @PostMapping("/{courseId}/bookmark")
    public CommonResponse<Boolean> addBookmark(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId) {
        log.info("添加课程收藏 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("添加课程收藏失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("添加课程收藏失败 - 课程不存在, 课程ID: {}", courseId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
            }
            
            // 检查是否已收藏
            QueryWrapper<CourseBookmark> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id", courseId).eq("student_id", studentId);
            Long count = courseBookmarkMapper.selectCount(wrapper);
            
            if (count != null && count > 0) {
                log.info("添加课程收藏失败 - 已经收藏过, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "已经收藏过该课程", true);
            }
            
            // 添加收藏记录
            CourseBookmark bookmark = new CourseBookmark();
            bookmark.setCourseId(courseId);
            bookmark.setStudentId(studentId);
            bookmark.setCreatedAt(LocalDateTime.now());
            
            int result = courseBookmarkMapper.insert(bookmark);
            if (result > 0) {
                log.info("添加课程收藏成功 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "收藏成功", true);
            } else {
                log.warn("添加课程收藏失败 - 插入数据库失败, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "收藏失败");
            }
        } catch (Exception e) {
            log.error("添加课程收藏异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
            System.out.println("添加课程收藏异常详细信息：");
            e.printStackTrace();
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "收藏失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除课程收藏
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @return 操作结果
     */
    @DeleteMapping("/{courseId}/bookmark")
    public CommonResponse<Boolean> removeBookmark(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId) {
        log.info("删除课程收藏 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("删除课程收藏失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("删除课程收藏失败 - 课程不存在, 课程ID: {}", courseId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
            }
            
            // 检查是否已收藏
            QueryWrapper<CourseBookmark> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id", courseId).eq("student_id", studentId);
            Long count = courseBookmarkMapper.selectCount(wrapper);
            
            if (count == null || count == 0) {
                log.info("删除课程收藏失败 - 未收藏过, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "未收藏过该课程", true);
            }
            
            // 删除收藏记录
            int result = courseBookmarkMapper.delete(wrapper);
            if (result > 0) {
                log.info("删除课程收藏成功 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "取消收藏成功", true);
            } else {
                log.warn("删除课程收藏失败 - 从数据库删除失败, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消收藏失败");
            }
        } catch (Exception e) {
            log.error("删除课程收藏异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
            System.out.println("删除课程收藏异常详细信息：");
            e.printStackTrace();
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消收藏失败: " + e.getMessage());
        }
    }
}